package com.liguang.rcs.admin.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class JacksonUtil {
    private static ObjectMapper mapper = new ObjectMapper();
    static {
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_EMPTY);
    }

    public static <T> T toObject(String json, TypeReference<T> typeReference) {

        if (Strings.isNullOrEmpty(json) || typeReference == null) {
            return null;
        }
        try {
            return mapper.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("toObject fail, Exception:", e);
            return null;
        }
    }
    public static <T> T toObject(String json, Class<T> clazz) {
        if (Strings.isNullOrEmpty(json) || clazz == null) {
            return null;
        }
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("toObject fail, Exception:", e);
            return null;
        }
    }

    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("toJson fail, Exception:", e);
            return null;
        }
    }

}
